#include "StdAfx.h"
#include <stdlib.h>
#include "RandomInterleaver.h"
#include "rng.h"

CRandomInterleaver::CRandomInterleaver(uint32_t size)
{
	mInterleaveIndex = new uint32_t[size];
	mDeInterleaveIndex = new uint32_t[size];
	mSize = size;
	if(mInterleaveIndex!=NULL)
	{
		//initialize
		for(uint32_t i=0;i<size;i++){
			mInterleaveIndex[i] = 0xFFFFFFFF;
		}
		//create random interleaving index
		for(uint32_t i=0;i<size;i++){
            uint32_t index = gRNG.rand_halfclosed01() * (size-1); 
			if(mInterleaveIndex[index]==0xFFFFFFFF){
				//free slot
				mInterleaveIndex[index] = i;
				mDeInterleaveIndex[i] = index;
			}else{
				//flip a coin => 0 = left, 1= right
                bool coin =gRNG.rand_closed01() > 0.5; 
				if(coin){
					//right
					while(mInterleaveIndex[index]!=0xFFFFFFFF){
						index = (index + 1) % size;
					}
				}else{ //left
					while(mInterleaveIndex[index]!=0xFFFFFFFF){
						if(index>0){
							index--;
						}else{
							index = size-1;
						}
					}
				}
				mInterleaveIndex[index] = i;
				mDeInterleaveIndex[i] = index;
				
			}
		}
	}
    //debug
	//FILE* arq;
	//			arq = (fopen("int1.txt","w"));
	//			for(uint32_t i=0;i<size;i++){
	//				fprintf(arq,"%d ",mInterleaveIndex[i]);
	//			}
	//			fclose(arq);
};